﻿using System.IO;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System;
using System.Web;
using System.Net;
using Microsoft.Owin;

namespace CmdHost
{
    public class CommonAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// action 执行之前 进行处理
        /// </summary>
        /// <param name="actionContext"></param>
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            //身份认证，Token 处理
            var name = actionContext.ActionDescriptor.ActionName;
            // Log the call
            Console.WriteLine("WebAPI:" + name+"  IP： " + GetClientIpAddress(actionContext.Request));

        }
        public static string GetClientIpAddress(HttpRequestMessage request)
        {
            if (request.Properties.ContainsKey("MS_HttpContext"))
            {
                return IPAddress.Parse(((HttpContextBase)request.Properties["MS_HttpContext"]).Request.UserHostAddress).ToString();
            }
            if (request.Properties.ContainsKey("MS_OwinContext"))
            {
                return IPAddress.Parse(((OwinContext)request.Properties["MS_OwinContext"]).Request.RemoteIpAddress).ToString();
            }
            return null;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="actContext"></param>
        public override void OnActionExecuted(HttpActionExecutedContext actContext)
        {
            if (actContext.Exception != null)
                return;
            base.OnActionExecuted(actContext);
            //统一返回格式
            ApiResultModel result = new ApiResultModel();
            // 取得由 API 返回的状态代码
            result.Status = actContext.ActionContext.Response.StatusCode;
            // 取得由 API 返回的资料
            result.Data = actContext.ActionContext.Response.Content.ReadAsAsync<object>().Result;
            // 重新封装回传格式
            actContext.Response = actContext.Request.CreateResponse(result.Status, result);

            var content = actContext.Response.Content;
            var bytes = content == null ? null : content.ReadAsByteArrayAsync().Result;
            var zlibbedContent = bytes == null ? new byte[0] : CompressionHelper.DeflateByte(bytes);
            actContext.Response.Content = new ByteArrayContent(zlibbedContent);
            actContext.Response.Content.Headers.Remove("Content-Type");
            actContext.Response.Content.Headers.Add("Content-encoding", "deflate");
            actContext.Response.Content.Headers.Add("Content-Type", "application/json");

        }
    }
    public class CompressionHelper
    {
        public static byte[] DeflateByte(byte[] str)
        {
            if (str == null)
            {
                return null;
            }

            using (var output = new MemoryStream())
            {
                using (
                    var compressor = new Ionic.Zlib.DeflateStream(
                    output, Ionic.Zlib.CompressionMode.Compress,
                    Ionic.Zlib.CompressionLevel.BestSpeed))
                {
                    compressor.Write(str, 0, str.Length);
                }

                return output.ToArray();
            }
        }
    }


}
